package org.apache.rocketmq.client.codecoord.producer;

import org.apache.rocketmq.client.codecoord.RocketMqConstant;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

/**
 * 同步消息发送
 *
 * @author tianxincoord@163.com
 * @since 2021/10/25
 */
public class BasicSyncMessageSend {

    public static void main(String[] args) throws Exception {
        BasicSyncMessageSend messageSend = new BasicSyncMessageSend();
        messageSend.syncProducer();
    }

    /**
     * Producer端发送同步消息
     * 这种可靠性同步地发送方式使用的比较广泛，比如：重要的消息通知，短信通知
     */
    public void syncProducer() throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer(RocketMqConstant.GROUP);
        producer.setNamesrvAddr(RocketMqConstant.NAME_SRV_ADDRESS);
        producer.setRetryTimesWhenSendFailed(2);
        producer.setSendMsgTimeout(5000);
        producer.start();

        long timeMillis = System.currentTimeMillis();
        byte[] bytes = ("Hello RocketMQ " + timeMillis).getBytes(RemotingHelper.DEFAULT_CHARSET);
        Message msg = new Message(RocketMqConstant.TOPIC, RocketMqConstant.TAG, bytes);
        msg.setKeys(String.valueOf(timeMillis));
        SendResult sendResult = producer.send(msg);
        System.out.printf("【%s】%s%n", new String(bytes), sendResult);

        producer.shutdown();
    }
}
